﻿using AutoMapper;
using Common;
using Common.Dtos;
using Common.LayPage;
using Newtonsoft.Json;
using Sigma.Admin.API.Context.Entity;
using Sigma.Admin.API.Context.UnitOfWork;

namespace Sigma.Admin.API.Services
{
    public class UserService : IUserService
    {
        private readonly IUnitOfWork _work;
        private readonly IMapper _mapper;
        

        public UserService(IUnitOfWork work, IMapper mapper)
        {
            _work = work;
            _mapper = mapper;
        }

        /// <summary>
        /// 查出id和插入model是一个事务，最好加锁或开启事务
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResponse> AddAsync(UsersDto model)
        {
            try
            {
               var _repository = _work.GetRepository<UserEntity>();
                var user = _mapper.Map<UserEntity>(model);
                var exist = _repository.Exists( x => x.Account == model.Account);
                
                if (exist)
                {
                    return  new ApiResponse("已存在用户账号或用户名");
                }
                user.CreateTime = DateTime.Now;
                user.UpdateTime = DateTime.Now;
                _repository.Insert(user);
                 var res =await _work.SaveChangesAsync();
                if(res>0)
                    return new ApiResponse("添加成功", true);
                return new ApiResponse("添加失败");
            }
            catch(Exception ex)
            {
                return new ApiResponse("操作失败："+ex.Message);
            }
            
            
        }

        public Task<ApiResponse<List<UsersDto>>> GetAllAsync()
        {
            try
            {
                var _repository = _work.GetRepository<UserEntity>();
                var users = _repository.GetAll().ToList();
                var dto = _mapper.Map<List<UsersDto>>(users);
                return Task.FromResult(new ApiResponse<List<UsersDto>>(null, true, dto));
            }
            catch(Exception ex)
            {
                return Task.FromResult(new ApiResponse<List<UsersDto>>("操作失败：" + ex.Message));
            }
            

        }

        public Task<ApiResponse> DeleteAsync(List<UsersDto> id)
        {
            try
            {
                var respo =_work.GetRepository<UserEntity>();
                var list = new List<UserEntity>();
                id.ForEach(x =>
                {
                    list.Add(_mapper.Map<UserEntity>(x));
                });
                respo.Delete(list);
                var res =_work.SaveChangesAsync();
                if (res.Result > 0)
                {
                    return Task.FromResult(new ApiResponse($"操作成功", true));
                }
                return Task.FromResult(new ApiResponse($"操作失败"));
            }
            catch(Exception e)
            {
                return Task.FromResult(new ApiResponse($"操作失败：{e.Message}"));
            }
            return Task.FromResult(new ApiResponse("该功能尚在开发中..."));
        }

        public Task<ApiResponse> DeleteAsync(UsersDto id)
        {
            return Task.FromResult(new ApiResponse("该功能尚在开发中..."));
        }


        /// <summary>
        /// 分页查询，暂时不用
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public Task<ApiResponse> GetAllAsync(QueryParameter query)
        {
            return Task.FromResult(new ApiResponse("该功能尚在开发中..."));
        }

        

        public Task<ApiResponse> GetSingleAsync(int id)
        {
            return Task.FromResult(new ApiResponse("该功能尚在开发中..."));
        }

        public Task<ApiResponse> UpdateAsync(List<UsersDto> model)
        {
            try
            {
                if (model.Count == 0 || model == null)
                    return Task.FromResult(new ApiResponse("更新内容不能为控"));

                var _repository = _work.GetRepository<UserEntity>();
                var datas = new List<UserEntity>();
                model.ForEach(x =>
                {
                    var ent = _repository.GetFirstOrDefault(predicate: y => y.Id.Equals(x.Id), disableTracking: false);
                    if (ent is not null)
                    {
                        ent.Account = x.Account;
                        ent.UserName = x.UserName;
                        ent.UpdateTime = DateTime.Now;
                        datas.Add(ent);
                    }
                });
                if (datas.Count != 0)
                {
                    _repository.Update(datas);
                    var res = _work.SaveChanges();
                    if (res > 0)
                        return Task.FromResult(new ApiResponse($"更新了{res}条数据",true));
                }

                return Task.FromResult(new ApiResponse("更新失败！"));
            }
            catch(Exception e)
            {
                return Task.FromResult(new ApiResponse($"操作异常：{e.Message}"));
            }
            
        }

        public Task<ApiResponse> EditKeysAsync(UsersDto dto)
        {
            try
            {
                var repo =_work.GetRepository<UserEntity>();
                var user = repo.GetFirstOrDefault(predicate: x => x.Id.Equals(dto.Id),disableTracking:false);
                user.PermissionKey = JsonConvert.SerializeObject(dto.PermissionKey);
                var res =_work.SaveChanges();
                if (res > 0)
                {
                    return Task.FromResult(new ApiResponse("修改成功", true));
                }
                return Task.FromResult(new ApiResponse("操作失败"));
            }
            catch(Exception e)
            {
                return Task.FromResult(new ApiResponse($"操作失败{e.Message}"));
            }
        }
    }
}
